package com.nio;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.Scanner;

/**
 * @description
 * @author: wangtao
 * @date:17:16 2018/12/20
 * @email:taow02@jumei.com
 */
@ChannelHandler.Sharable //1
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {


	private String person;

	public EchoClientHandler(String person) {
		this.person = person;
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true){
					String msg = new Scanner(System.in).next();
					ctx.writeAndFlush(Unpooled.copiedBuffer(person + ":" + msg, //2
							CharsetUtil.UTF_8));
				}
			}
		}).start();
	}

	@Override
	protected void messageReceived(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
		System.out.println("Client received: " + in.toString(CharsetUtil.UTF_8)); //3
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
		System.out.println("client read complete");
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { //4
		cause.printStackTrace();
		ctx.close();
	}

}